package com.edushare.common.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.Cookie;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edushare.common.exceptions.EduShareRuntimeException;
import com.edushare.common.vo.Users;

public class CookieUtils {
	
	public static final String COOKIE_KEY_USER_NAME 					= "un";

	public static Log log = LogFactory.getLog(CookieUtils.class);
	
	public static Cookie createUserNameCookie(Users u){
		log.debug("creating user-name cookie");
		if(!StringUtil.isValid(u.getUserName())){
			log.error("CAN'T CREATE A USER_NAME COOKIE. USER NAME CAN'T BE NULL. MUST BE AN INVALID USER.");
			throw new IllegalStateException("CAN'T CREATE A USER_NAME COOKIE. USER NAME CAN'T BE NULL. MUST BE AN INVALID USER.");
		}
		
		String encryptedName="";
		try {
			encryptedName = CryptionUtil.encrypt(u.getUserName());
		} catch (Exception e) {
			log.error("ERROR DURING ENCRYPTION.",e);
			throw new EduShareRuntimeException("ERROR DURING ENCRYPTION.");
		}
		return new Cookie(COOKIE_KEY_USER_NAME, encryptedName);
	}
	
	public static String getUserNameFromCookie(Cookie[] cookies){
		String user = null;
		for(Cookie cookie: cookies){
			if(cookie.getName().equals(COOKIE_KEY_USER_NAME)){
				try {
					user = CryptionUtil.decrypt(cookie.getValue());
				} catch (Exception e) {
					log.error("UNABLE TO DECRYPT.",e);
				}
				break;
			}
		}
		
		return user;
	}
}
